from db_connect import ConnMysqlSlave
from db_connect import ConnMysql
import aiomysql


class Order():

    def __init__(self, order_id, status):

        self.order_id = order_id
        self.status = status
        # self.result = self.main()


    async def result(self):

        #判断所传参数是否为空
        if not (self.order_id and self.status):

            return {
                'status': -1,
                'errorCode': 701,
                'errorMsg': '参数不能为空',
                'resultBody': None,
            }
        #参数必须为数字
        if not (self.order_id.isdigit()):

            return {
                'status': -1,
                'errorCode': 1102,
                'errorMsg': '参数必须为数字',
                'resultBody': None,
            }
        
        #从进程池里取链接对象
        async with ConnMysqlSlave().pool.acquire() as c:

            #检测连接对象是否连接
            await c.ping()
            #游标的上下文管理
            async with c.cursor(aiomysql.DictCursor) as cur:

                sql = "SELECT * FROM orders WHERE id=%s "
                await cur.execute(sql, (self.order_id,))
                select_info = await cur.fetchone()
        if select_info == None:

            return {
                'status': -1,
                'errorCode': 702,
                'errorMsg': "订单号不存在",
                'resultBody': None,
            }

        #从进程池里取链接对象
        async with ConnMysql().pool.acquire() as c:

            #检测连接对象是否连接
            await c.ping()
            #游标的上下文管理
            async with c.cursor(aiomysql.DictCursor) as cur:

                sql = "UPDATE orders SET status=%s WHERE id=%s;"
                await cur.execute(sql, (self.status,self.order_id))
                await c.commit()


        return {
            'status': 1,
            'errorCode': None,
            'errorMsg': None,
            'resultBody': "ok",
        }